
import flash.events.TimerEvent;
import flash.utils.Timer;

import mx.rpc.events.ResultEvent;

	/* actionscript associated with mxml file
	 */
	
	public var gameTimer:Timer = new Timer(500);
	public var counter:Number;
	private var countdown:Number = 15;
	
	[Bindable]public var task_request:String = "default";
	[Bindable]public var playerID_request:Number = 0;
	[Bindable]public var name_request:String = "";
	[Bindable]public var crisisID_request:Number = 0;
	[Bindable]public var responseCode_request:Number = 0;
		
	public var playerName:String;
	public var playerID:Number;
	public var playerScore:Number;
	
	[Bindable]public var playerInfo:String;
	
	private var currentCrisis:Number;
	private var currentCrisisOutcome:Number;
	private var currentCrisisResponse:Number;
	private var currentOpponentID:Number;
	
	public var currentSession:Number; //make setter function to check when this changes
	
	public var introChatter:IntroChatter = new IntroChatter();
	public var idleChatter:IdleChatter = new IdleChatter();
	
	private var ticksToNextCrisis:Number;
	
	
	public function EnterIntroState():void
	{
		gameTimer.start();
		gameTimer.addEventListener(TimerEvent.TIMER,IntroStateTick);
		counter = 0;
		
	}
	
	public function IntroStateTick (e:TimerEvent):void
	{
		if (counter < introChatter.lenght)
		{
			intro.buffer = introChatter.getNext();
			counter++;
		}
		else if (counter < introChatter.lenght + 2)
		{
			counter++;
		}				
		else
		{
			enterPlayerName.visible = true;
			enterPlayerName.setFocus();
			counter++;
		} 
	}
	
	public function ExitIntroState():void
	{
		gameTimer.removeEventListener(TimerEvent.TIMER, IntroStateTick);
		counter = 0;
	}
	
	public function EnterPlayState():void
	{
		gameTimer.addEventListener(TimerEvent.TIMER, PlayStateTick);
		ticksToNextCrisis = Math.round(Math.random()*20)+10;
	}
	
	public function PlayStateTick(e:TimerEvent):void
	{
		counter++;
		trace ("tick "+ counter);
		
		if (counter % 2 == 0)
			{
			UpdatePlayerStatus();
			}
		if (counter % 5 == 0)
			{
			//trace ("updating player list");
			UpdatePlayerList();
			happeningNow.buffer = idleChatter.getNext();
			}
		if (counter % ticksToNextCrisis == 0)
			{
			//trace ("creating crisis");
			CreateCrisis();
			}
		
	}
	
	public function ExitPlayState():void
	{
		gameTimer.removeEventListener(TimerEvent.TIMER, PlayStateTick);
	}

	public function EnterCrisisState():void
	{
		gameTimer.removeEventListener(TimerEvent.TIMER, PlayStateTick);
		gameTimer.addEventListener(TimerEvent.TIMER, CrisisStateTick);
		counter = 0;
		button_Escalate.enabled = true;
		button_StandDown.enabled = true;
		
		
		happeningNow.wipeText();
		happeningNow.buffer = "Awaiting decision...";
		
		countdown = 15;
		
	}

	public function CrisisStateTick(e:TimerEvent):void
	{
		counter++; 
		trace ("crisis Tick " + counter);
		
		if (counter%2 == 0)
			{
				UpdateCrisisStatus();
				happeningNow.buffer = "\n" + countdown + "...";
				countdown--;
			}
		
		if (countdown == 0)
		{
			//flag the opponent as idle and go back to play state
			ReportIdleOpponent();
			UpdatePlayerStatus();
			countdown = -1;
			
		}
		
		
		
	}
	
	public function StandDown():void
	{
		button_Escalate.enabled = false;
		button_StandDown.enabled = false;
		
		happeningNow.buffer = "\nAwaiting reply...";
		
		task_request = "respond";
		responseCode_request = 1;
		currentCrisisResponse = responseCode_request;
		crisisID_request = currentCrisis;
		
		respondToCrisisResource.send();
	}
	
	public function Escalate():void
	{
		button_StandDown.enabled = false;
		button_Escalate.enabled = false;
		
		happeningNow.buffer = "\nAwaiting reply...";
		
		task_request = "respond";
		responseCode_request = 3;
		currentCrisisResponse = responseCode_request;
		crisisID_request = currentCrisis;
		
		respondToCrisisResource.send();
	}
	
	public function ReportIdleOpponent():void
	{
		task_request = "report_idle_opponent";
		playerID_request = currentOpponentID;
		crisisID_request = currentCrisis;
		
		setIdleResource.send();
	}
	
	public function ReportIdleSelf():void
	{
		task_request = "report_idle_opponent";
		playerID_request = playerID;
		crisisID_request = currentCrisis;
		
		setIdleResource.send();
	}
	
	public function ReportActivePlayer():void
	{
		task_request = "report_active_player";
		playerID_request = playerID;
		
		unsetIdleResource.send();
	}
	
	public function UpdateCrisisStatus():void
	{
		task_request = "update_crisis";
		crisisID_request = currentCrisis;
		
		updateCrisisResource.send();
	}
	
	public function CrisisStatusUpdated(e:ResultEvent):void
	{
		Session = e.result.sessionID;
		
		Outcome = e.result.outcome;
		
		
		if (playerID == e.result.first_player_id)
			currentOpponentID = e.result.second_player_id;
		else
			currentOpponentID = e.result.first_player_id;
		
	}
	
	public function ExitCrisisState():void
	{
		gameTimer.removeEventListener(TimerEvent.TIMER, CrisisStateTick);
		gameTimer.addEventListener(TimerEvent.TIMER, PlayStateTick);
		counter = 0;
	}
	 
	public function StartPlayerAdd():void
	 {
	 	name_request = enterPlayerName.text;
	 	var pattern:RegExp = /\W/g ; //avoid injections
	 	name_request = name_request.replace(pattern,"");
	 	
	 	task_request = "add_player";
	 	addPlayerResource.send();
	 	
	 	
	  }
	 
	private function PlayerAdded(e:ResultEvent):void
	{
	 	playerID = e.result.playerID;
	 	playerName = e.result.playerName;
	 	currentSession = e.result.sessionID;
	 	
	 	trace ("playerID = " + playerID);
	 	trace ("sessionID = " + currentSession);
	 	currentState = 'Play';
	 }
	 
	public function UpdatePlayerList():void
	 {
	 	trace ("REQ: update player list");
	 	task_request = "update_player_list";
	 	updatePlayerListResource.send();
	 	//updatePlayerListResource.addEventListener(ResultEvent.RESULT, PlayerListUpdated);
	 	
	 }
	
	public function PlayerListUpdated (e:ResultEvent):void
	{
		//updatePlayerListResource.removeEventListener(ResultEvent.RESULT, PlayerListUpdated);
		trace ("REPL: update player list");
		playerList.dataProvider = e.result.players.player;
		
		Session = e.result.sessionID;
	}
	
	public function UpdatePlayerStatus ():void
	{
		trace ("REQ: update player status");
		task_request = "update_status";
		playerID_request = playerID;
		
		updatePlayerStatusResource.send();
		//updatePlayerStatusResource.addEventListener(ResultEvent.RESULT, PlayerStatusUpdated);
		
		
		
	}
	 
	public function PlayerStatusUpdated(e:ResultEvent):void
	{
		// crisis and session
		
		//updatePlayerStatusResource.removeEventListener(ResultEvent.RESULT, PlayerStatusUpdated);
		
		trace ("REPL: update player status");
		playerScore = e.result.score;
		
		playerInfo = "CALLSIGN: "+playerName+ " - INFLUENCE: "+playerScore; 
		
		Crisis = e.result.currentCrisis;
				
		Session = e.result.sessionID;
	}
	
	public function CreateCrisis ():void
	{
		
		task_request = "add_crisis";
		playerID_request = playerID;
		trace ("REQ: create a crisis - PID:"+playerID_request);
		addCrisisResource.send();
		//addCrisisResource.addEventListener(ResultEvent.RESULT,PlayerStatusUpdated);//link to function that will update the status
	}
	
	
	 
	public function set Session (val:Number):void
	{
		if (val != currentSession)
			currentState = "End";
			
	}
	
	public function set Crisis (val:Number):void
	{
		if (val != 0)
		{
			currentCrisis = val;
			currentState = "Crisis";
		}
		else
		{
			currentCrisis = val;
			currentState= "Play";
		}
	}
	
	public function set Outcome (val:Number):void
	{
		if (val != currentCrisisResponse)
		{
			switch (val)
			{
				case 2:
					happeningNow.buffer = "CRISIS DEFUSED.\nInfluence gained: 3.";
					break;
				case 4:
					if (currentCrisisResponse == 1)
						happeningNow.buffer = "CRISIS LOST.\nNo influence gained.";
					else
						happeningNow.buffer = "CRISIS WON!\nInfluence gained: 10.";
					break;
				case 6:
					happeningNow.buffer = "OH NO! GLOBAL THERMONUCLEAR WAR INITIATED";
			}
		}
	}